package com.siwei.mes.job.laborator;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.base.BaseParams;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.MacTools;
import com.siwei.mes.entity.DownloadLaboratoryEntity;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKyqd;
import com.siwei.mes.enums.*;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.experiment.ExperimentMapper;
import com.siwei.mes.mapper.laboratory.ConcreteLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.WTSampleMapper;
import com.siwei.mes.service.laboratory.UploadAndDownloadAssociationService;
import com.siwei.mes.service.system.SystemParamService;
import com.siwei.mes.sync.config.SyncProcessorService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时下载混凝土抗压试验数据
 **/
@Component
public class ScheduledDownloadXhJob {
    private static final Logger log = LoggerFactory.getLogger("job");
    @Resource
    private ExperimentMapper experimentMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;
    @Resource
    private SystemParamService systemParamService;
    @Resource
    private ConcreteLaboratoryMapper concreteLaboratoryMapper;
    @Resource
    private WTSampleMapper wtSampleMapper;
    @Resource
    private UploadAndDownloadAssociationService uploadAndDownloadAssociationService;
    @Resource
    private SyncProcessorService syncProcessorService;

    //@Scheduled(cron = "0 0/5 * * * ?")
    @Scheduled(fixedRate = 3600000)
    public void init() {
        String operSystem = MacTools.getOperSystem();
        if (Arrays.stream(BaseParams.MAC_LIST).parallel().anyMatch(operSystem::contains)) {
            return;
        }
        log.info("拉取协会混凝土抗压数据到品控定时任务开始！");
        String systemParamValue = systemParamService.selectBySystemCode(SystemParamEnum.PULL_XH_DATA_TO_MES_JOB, "0");
        if (StringUtils.isBlank(systemParamValue) || "0".equals(systemParamValue)) {
            log.info("系统参数：【{}】拉取协会混凝土抗压数据到品控定时任务，暂未开启推，不拉取协会数据！", SystemParamEnum.PULL_XH_DATA_TO_MES_JOB);
            return;
        }
        try {

            //默认查询30天的
            Date currentDate = new Date();
            Date startDate = new Date(currentDate.getTime() - 30L * 24 * 60 * 60 * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String beginTime = sdf.format(startDate);
            String comTime = sdf.format(currentDate);

            //抗压
            Experiment expKy = new Experiment().setExperimentType(MaterialsEnum.CONCRETE.getCode()).setCheckType(CheckEnum.BATCH.getCode())
                    .setExperimentStatus(ExperimentStatusEnum.IN_TEST.getCode()).setEntrustExperimentBlur(TestProjectEnum.CONCRETE_PARAM_KYQD.getName());
            List<Experiment> experimentList = experimentMapper.getList(expKy);


            //抗渗
            Experiment expKs = new Experiment().setExperimentType(MaterialsEnum.CONCRETE.getCode()).setCheckType(CheckEnum.BATCH.getCode())
                    .setExperimentStatus(ExperimentStatusEnum.IN_TEST.getCode()).setEntrustExperimentBlur(TestProjectEnum.CONCRETE_PARAM_KSDJ.getName());
            List<Experiment> experimentKsList = experimentMapper.getList(expKs);

            //抗折
            Experiment expKz = new Experiment().setExperimentType(MaterialsEnum.CONCRETE.getCode()).setCheckType(CheckEnum.BATCH.getCode())
                    .setExperimentStatus(ExperimentStatusEnum.IN_TEST.getCode()).setEntrustExperimentBlur(TestProjectEnum.CONCRETE_PARAM_KZQD.getName());
            List<Experiment> experimentKzList = experimentMapper.getList(expKz);


            log.info("自动下载混凝土抗压协会数据开始!，条数：【{}】", experimentList.size());
            for (Experiment experiment : experimentList) {
                if (StringUtils.isBlank(experiment.getConsignId())) {
                    log.info("自动下载混凝土抗压协会数据,委托id：【{}】，委托编号：【{}】协会委托为空 则不处理！", experiment.getId(), experiment.getExperimentNo());
                    continue;
                }
                DownloadLaboratoryEntity entity = new DownloadLaboratoryEntity()
                        .setExperimentId(Collections.singletonList(String.valueOf(experiment.getId())));
                syncProcessorService.submitRequest(entity);
            }
            log.info("自动下载混凝土抗压协会数据结束!");

            log.info("自动下载混凝土抗渗协会数据开始!，条数：【{}】", experimentKsList.size());
            for (Experiment experiment : experimentKsList) {
                if (StringUtils.isBlank(experiment.getConsignId())) {
                    log.info("自动下载混凝土抗渗协会数据,委托id：【{}】，委托编号：【{}】协会委托为空 则不处理！", experiment.getId(), experiment.getExperimentNo());
                    continue;
                }
                DownloadLaboratoryEntity entity = new DownloadLaboratoryEntity()
                        .setExperimentId(Collections.singletonList(String.valueOf(experiment.getId())));
                syncProcessorService.submitRequest(entity);
            }
            log.info("自动下载混凝土抗渗协会数据结束!");

            log.info("自动下载混凝土抗折协会数据开始!，条数：【{}】", experimentKzList.size());
            for (Experiment experiment : experimentKzList) {
                if (StringUtils.isBlank(experiment.getConsignId())) {
                    log.info("自动下载混凝土抗折协会数据,委托id：【{}】，委托编号：【{}】协会委托为空 则不处理！", experiment.getId(), experiment.getExperimentNo());
                    continue;
                }
                DownloadLaboratoryEntity entity = new DownloadLaboratoryEntity()
                        .setExperimentId(Collections.singletonList(String.valueOf(experiment.getId())));
                syncProcessorService.submitRequest(entity);
            }
            log.info("自动下载混凝土抗折协会数据结束!");
        } catch (Exception e) {
            log.error("定时下载协会混凝土抗压试验数据异常：" + e.getMessage(), e);
        }


    }


    //试验
    public void finishTest(String sampleNo, List<ExperimentDetail> list, Experiment experiment) {

        //循环试验结果数据
        for (ExperimentDetail detail : list) {

            //品控试验json
            JSONObject objJson = detail.getObjJson();

            if (detail.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KYQD.getCode())) {
                ConcreteKyqd concreteKyqd = objJson.toJavaObject(ConcreteKyqd.class);


                //龄期
                String lq = null;
                if (concreteKyqd != null && StringUtils.isNotBlank(concreteKyqd.getLq())) {
                    lq = concreteKyqd.getLq();
                }

                if (StringUtils.isBlank(lq)) {
                    log.info("品控混凝土抗压试验龄期值为空，试验委托为：" + experiment.getExperimentNo());
                    return;
                }
                if (experiment.getEntrustTime() == null) {
                    log.info("品控混凝土抗压试验委托日期值为空，试验委托为：" + experiment.getExperimentNo());
                    return;
                }

                //委托日期
                Date entrustTime = experiment.getEntrustTime();
                int daysToAdd = Integer.parseInt(lq);

                //委托日期 + 临期
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(entrustTime);
                calendar.add(Calendar.DAY_OF_MONTH, daysToAdd);

                Calendar currentCalendar = Calendar.getInstance();
                currentCalendar.setTime(new Date());


                //大于当前 27天前的 记录日志
                Calendar instance = Calendar.getInstance();
                instance.setTime(new Date());  // 设置为当前时间
                instance.add(Calendar.DAY_OF_MONTH, -27);  // 往前推27天
                Date twentySevenDaysAgo = instance.getTime();
                if (entrustTime.before(twentySevenDaysAgo)) {
                    Date time = currentCalendar.getTime();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    String formattedDate = sdf.format(time);
                    log.info("试验台账 ： " + experiment.getExperimentNo() + "临期值为:" + lq + "将在" + formattedDate + "自动下载试验数据!");
                }

                //不等于当前时间的 则不下载
                if (calendar.get(Calendar.DAY_OF_MONTH) != currentCalendar.get(Calendar.DAY_OF_MONTH)) {
                    return;
                }


                //根据样品编码查询协会混凝土抗压强度信息
                Map<String, Object> data = concreteLaboratoryMapper.findDATA_JGCL_HNT_HNTKYBySampleNo(sampleNo);

                if (data == null) {
                    continue;
                }

                if (data.get("S2") != null) {
                    concreteKyqd.setPjz28d(data.get("S2").toString());
                }
                if (data.get("S3") != null) {
                    concreteKyqd.setFyxs28d(data.get("S3").toString());
                }

                if (data.get("S4") != null && data.get("S7") != null) {
                    concreteKyqd.setSjcc(data.get("S4").toString() + "*" + data.get("S7").toString() + "*" + data.get("S7").toString());
                }

                if (concreteKyqd.getQd28d() != null && concreteKyqd.getQd28d().size() != 0) {

                    List<ConcreteKyqd.QdInfo> qd28d = concreteKyqd.getQd28d();

                    for (ConcreteKyqd.QdInfo qdInfo : qd28d) {
                        if (qdInfo.getIndex() != null && "1".equals(qdInfo.getIndex())) {

                            if (data.get("S13") != null) {
                                qdInfo.setHz(data.get("S13").toString());
                            }
                            if (data.get("S16") != null) {
                                qdInfo.setQd(data.get("S16").toString());
                            }

                        } else if (qdInfo.getIndex() != null && "2".equals(qdInfo.getIndex())) {

                            if (data.get("S14") != null) {
                                qdInfo.setHz(data.get("S14").toString());
                            }
                            if (data.get("S17") != null) {
                                qdInfo.setQd(data.get("S17").toString());
                            }

                        } else if (qdInfo.getIndex() != null && "3".equals(qdInfo.getIndex())) {

                            if (data.get("S15") != null) {
                                qdInfo.setHz(data.get("S15").toString());
                            }
                            if (data.get("S18") != null) {
                                qdInfo.setQd(data.get("S18").toString());
                            }

                        }
                    }
                }

                //对象转json
                JSONObject jsonObject = JsonUtils.beanToObject(concreteKyqd);

                //重新赋值
                detail.setObjJson(jsonObject);

                //修改品控试验数据
                experimentDetailMapper.updateByPrimaryKeySelective(detail);


                //查询协会委托状态
                Map<String, Object> wtSampleList = wtSampleMapper.findWTSampleList(sampleNo);

                if (wtSampleList == null) {
                    log.error("协会台账数据有误，未查询到协会台账信息... 协会样品id：" + sampleNo + "品控台账编号：" + experiment.getExperimentNo());
                    continue;
                }
                //如果协会为已完成 则更新品控为已完成
                if (wtSampleList != null && wtSampleList.get("Sample_Status") != null && "1".equals(wtSampleList.get("Sample_Status").toString())) {
                    experiment.setExperimentStatus(ExperimentStatusEnum.FINISH.getCode());
                    experimentMapper.updateByPrimaryKeySelective(experiment);
                }

            } else if (detail.getTestProjectCode().equals(TestProjectEnum.SLAG_PARAM_KZF_HXZS.getCode())) {

            }


        }


    }
}








